<?php
namespace catchAdmin\externalGoods\model;

use catchAdmin\externalGoods\model\TenantGoodsRule as TenantGoodsRule;
use catchAdmin\externalGoods\model\TenantGoodsAttr as TenantGoodsAttr;
use catchAdmin\externalGoods\model\search\TenantGoodsSearch;
use catcher\base\CatchModel;
use catcher\CatchAuth;
use think\Exception;
use think\facade\Db;

class TenantGoods extends CatchModel
{

    use TenantGoodsSearch;

    protected $name = 'db_tenant_goods';
    protected $field = [
        'id',
        'syst_goods_id',
        'goods_spu',
        'goods_name',
        'goods_subtitle',
        'goods_keywords',
        'goods_img',
        'goods_slideshow_img',
        'barcode',
        'brand_id',
        'brand_name',
        'sync_brand_id',
        'sync_brand_name',
        'origin_id',
        'origin_name',
        'trade_type_id',
        'trade_type_name',
        'unit_name',
        'unit_id',
        'is_sale',
        'is_sys_api',
        'category_id',
        'sync_category_id',
        'sync_category_id_path',
        'sync_category_name',
        'description',
        'spec',
        'price',
        'cost_price',//成本价
        'market_price',
        'weight',
        'stock',
        'create_mode',
        'supplier_id',
        'created_at',
        'updated_at',
        'deleted_at',
        'tenant_id',
        'creator_id'
    ];

//    public function getResourceList($tenant_id=0)
//    {
//        $where = [];
//        if($tenant_id !== 0){
//            $where[]=['tenant_id','=',$tenant_id];
//        }
//
//        return $this->field('*')
//            ->catchSearch()
//            ->where($where)
//            ->order($this->aliasField('id'), 'desc')
//            ->paginate()
//            ;
//    }

    public function getList($tenant_id = 0)
    {
        $where = [];
        if($tenant_id !== 0){
            $where[]=['tenant_id','=',$tenant_id];
        }

        return $this
            ->withoutField('updated_at,deleted_at,tenant_id,creator_id,cost_price')
            ->catchSearch()
            ->where($where)
            ->order($this->aliasField('id'), 'desc')
            ->paginate()
            ->each(function (&$item) {
                $item['goods_pic'] = $item['goods_img'];//主图
                $goods_slideshow_img = array_merge([$item['goods_pic']], json_decode($item['goods_slideshow_img'],true));
                $item['goods_slideshow_img'] =$goods_slideshow_img;//轮播图包含主图

//                if(0 == $item['syst_goods_id']){//自建商品
//                    $_goods_id = $item['id'];
//                }else{
//                    $_goods_id = $item['syst_goods_id'];
//                }

                $item['attr'] = (new TenantGoodsAttr)
                    ->withoutField('created_at,updated_at,deleted_at,tenant_id,creator_id,create_mode')
                    ->where('goods_id',$item['id'])->select()->toArray();
                $item['rule'] = (new TenantGoodsRule)
                    ->withoutField('created_at,updated_at,deleted_at,tenant_id,creator_id,create_mode,cost_price')
                    ->where('goods_id',$item['id'])->select()->toArray();

//                $http_url = 'https://img.qekj.net/';
//
//                $item['goods_img'] = substr($item['goods_img'], 0, 4) === "http" ? $item['goods_img'] : $http_url . $item['goods_img'];
//                $item['goods_pic'] = $item['goods_img'];
//
//                $temp = [];
//                foreach ($item['goods_slideshow_img'] as $v){
//                    $temp[] =  substr($v, 0, 4) === "http" ? $v : $http_url . $v;
//                }
//                $item['goods_slideshow_img'] = $temp;

                //分类层级
                $item['cate_id_arr'] = (new Category)->where('id',$item['category_id'])->find()->cate_id_arr ?? [];
            });
    }

    public function apiGetList($tenant_id = 0,$paginate=true)
    {
        $where = [];
        if($tenant_id !== 0){
            $where[]=['tenant_id','=',$tenant_id];
        }

        $result =  $this
            ->field('goods_spu,
            id,
            syst_goods_id,
            goods_name,
            goods_subtitle,
            goods_keywords,
            goods_img,
            goods_slideshow_img,
            barcode,
            brand_id,
            brand_name,
            origin_id,
            origin_name,
            trade_type_id,
            trade_type_name,
            unit_id,
            unit_name,
            is_sale,
            category_id,
            sync_category_id_path as category_id_path,
            sync_category_name as category_name,
            description,
            price,
            stock')
            ->catchSearch()
            ->where($where)
            ->order($this->aliasField('id'), 'desc');

        if($paginate){
            $result = $result->paginate();
        }else{
            $result = $result->select()->toArray();
        }

        foreach ($result as &$item){
            if($item['category_name'] == ''){ //处理有些商品没有分类问题
                $item['category_name'] = json_encode((new Category)->where('id',$item['category_id'])->find()->cate_name_arr ?? [] ,JSON_UNESCAPED_UNICODE);
            }

            $item['goods_pic'] = $item['goods_img'];//主图
            $goods_slideshow_img = array_merge([$item['goods_pic']], json_decode($item['goods_slideshow_img'],true));
            $item['goods_slideshow_img'] =$goods_slideshow_img;//轮播图包含主图

            $item['attr'] = (new TenantGoodsAttr)
                ->field('attribute_id,name,attribute_name')
                ->where('goods_id',$item['id'])->select()->toArray();
            $item['rule'] = (new TenantGoodsRule)
                ->field('goods_sku,spec_sku,sku_name,sku_attribute_id,sku_attribute_name,sku_price,sku_stock')
                ->where('goods_id',$item['id'])->select()->toArray();

            unset($item['syst_goods_id']);
        }

        return $result;
    }

    public function getExportList(){
        $user =(new CatchAuth())->user();

        $where['tg.deleted_at'] = 0;
        //非管理员要商户id
        if($user['type'] !== 1 ){
            $where['tg.tenant_id'] = $user['tenant_id'];
        }

//        SUM(order_details.quantity * order_details.price) AS total_price')

        return $this->catchSearch()
            ->alias('tg')
            ->field('goods_spu,goods_name')
//            ->field("o.orderId,CONCAT(' ',orderId) as orderId2, o.orderDate,o.buyerName,o.ConsigneeCode,o.push_status,
//            GROUP_CONCAT(CONCAT(' ',od.order_no)) as order_no,
//            GROUP_CONCAT(od.goods_spu) AS goods_spu,
//            GROUP_CONCAT(od.goods_name SEPARATOR '\n') AS goods_name,
//            GROUP_CONCAT(od.sku_id) AS sku_id,
//            GROUP_CONCAT(od.deliver_money) AS deliver_money,
//            GROUP_CONCAT(od.tenant_total_money) AS tenant_total_money,
//            SUM(tenant_total_money) AS total_price")
//            ->leftJoin('db_customs_hn_order_detail od','od.order_id = o.id')
            ->where($where)
//            ->group('tg.id')
            ->select();
    }


}
